package service

import (
	"chess/global"
	"chess/model"
	"chess/utils"
	"errors"
	"log"
	"time"
)
type UserService struct {
}

//用户登录
func (s *UserService) Login(user *model.User) (*model.User, error) {
	if !utils.UserNameRe(user.UserName) {
		return nil, errors.New("参数不合法")
	}
	tmp := new(model.User)
	_, err := DBEngine.Where("user_name=?", user.UserName).Get(tmp)
	if err != nil {
		return nil, err
	}
	if !utils.ValidataPwd(user.PassWord, tmp.Salt, tmp.PassWord) {
		return nil, errors.New("账号或密码不正确")
	}
	//清除临时信息
	tmp.Token = utils.GetUUID()
	tmp.UpdateTime = time.Now()
	update, err := DBEngine.ID(tmp.Id).Cols("token").Update(tmp)
	if update>0 {
		//更新Token
		global.Lock.Lock()
		delete(global.AllUserByToken, tmp.Token)
		global.AllUserByToken[tmp.Token] = tmp

		delete(global.AllUserById, tmp.Id)
		global.AllUserById[tmp.Id] = tmp
		global.Lock.Unlock()
	}
	return tmp, nil
}
//用户注册
func (s *UserService) Register(user *model.User) (*model.User, error) {
	if !utils.UserRe(user) {
		return nil, errors.New("参数不合法")
	}
	tmp := model.User{}
	_, err := DBEngine.Where("user_name=? ", user.UserName).Get(&tmp)
	if err != nil {
		return nil, err
	}
	if tmp.Id > 0 {
		return nil, errors.New("该账号已经注册")
	}
	user.Salt = utils.GetUUID()
	user.PassWord = utils.MakeDbPwd(user.PassWord, user.Salt)
	user.CreateTime = time.Now()
	user.UpdateTime = time.Now()
	user.Token = utils.GetUUID()
	user.Status = "0"
	_, err = DBEngine.InsertOne(user)
	if err != nil {
		return nil, err
	}
	//更新缓存
	global.Lock.Lock()
	delete(global.AllUserByToken, user.Token)
	global.AllUserByToken[user.Token] = user

	delete(global.AllUserById, user.Id)
	global.AllUserById[user.Id] = user
	global.Lock.Unlock()

	return user, err
}
//根据token获取用户id并判断是否有效
func (s *UserService) GetIdByToken(token string) (int64, error) {
	id := s.GetIdByTokenCache(token)
	if id != 0 {
		return id, nil
	}
	u := new(model.User)
	_, err := DBEngine.Where("token=?", token).Get(u)
	if err != nil {
		return 0, err
	}
	if u.Id > 0 {
		return u.Id, nil
	}
	return 0, errors.New("没有找到用户")
}
//根据token获取临时信息
func (s *UserService) GetIdByTokenCache(token string) int64 {
	user, ok := global.AllUserByToken[token]
	if ok {
		return user.Id
	}
	return 0
}
//保存消息
func (s *UserService) SaveSingleMsg(msg *model.Message) bool {
	msg.Status = 0
	msg.CreateTime = time.Now()
	_, err := DBEngine.InsertOne(msg)
	if err != nil {
		log.Println(err.Error())
		return false
	}
	return true
}